<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use Illuminate\Session\Store;
use App\Http\Requests\Home\InforModifyRequest;
use App\Http\Controllers\Common\CommonController;
use App\Http\Requests\Home\PassRequest;
use App\Http\Requests\Home\AddressRequest;
use App\Http\Requests\Home\submitIntegralOrderRequest;
use Illuminate\Support\Facades\Redis;

/**
 * 前台个人中心
 * @author wuguoqing
 *
 */

class PersonalController extends Controller
{

	public function __construct() 
	{ 
		//session的中间件
		$this->middleware('homePersonal');

	}


	//个人中心首页
    public function personal()
    {
       

    	$id = session('user')['id'];
    	// dd(session('user'));
    	$state = [1 => '普通用户', 2 => 'vip用户', 3 => '砖石用户'];
    	$users = DB::table('users')
    				->select('name', 'user_level', 'total_intergral')
    				->where('id', $id)
    				->get();
    	
    	$users = DB::table('users')->select('name', 'user_level', 'total_intergral')->where('id', $id)->get();


    	$log = [0 => '未发出', 1 => '待揽收', 2 => '已发出'];
    	$orderState = [0 => '进行中', 1 => '已完成', 2 => '已取消'];

    	$orders = DB::table('orders')
    				->join('order_detail', 'orders.id', '=', 'order_detail.oid')
    				->select('order_detail.oid', 'order_detail.goods_pic', 'orders.pay_time', 'order_detail.product_num', 'orders.order_state', 'order_detail.item_price', 'orders.logistics')
    				->where('uid', $id)
    				->orderBy('order_detail.id', 'desc')
    				->take(3)
    				->get();
    	// dd($orders);

    	return view('Home/Personal/personal', [
    		'users' => $users,
    		'state' => $state,
    		'orders' => $orders,
    		'log' => $log,
    		'orderState' => $orderState,
    		]);
    }

    //个人信息
    public function information()
    {
    	$id = session('user')['id'];

    	$state = [1 => '普通用户', 2 => 'vip用户', 3 => '砖石用户'];
    	$users = DB::table('users')
    				->select('id', 'name', 'sex', 'phone', 'email', 'user_level')
    				->where('id', $id)
    				->get();

    	//dd($users);

    	return view('Home/Personal/information', ['users' => $users, 'state' => $state]);
    }


    //执行修改个人信息
    public function inforModify(InforModifyRequest $request)
    {
    	$common = new CommonController;
    	$id = session('user')['id'];
    	$sex = $request->input('sex');
    	$name = $request->input('name');
    	$phone = $request->input('phone');
    	$email = $request->input('email');

    	$patten = '/^((0?1[358]\d{9})|((0(10|2[1-3]|[3-9]\d{2}))?[1-9]\d{6,7}))$/';
        $match = preg_match($patten,$phone);
        if(!$match){
            return $common->json('errorTip','电话不规范');
        }

        $patten ='/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/';

        $match = preg_match($patten,$email);
        if (!$match) {
            return $common->json('errorTip','邮箱不规范');
        }

    	$res = DB::table('users')->where('id', $id)->update([
    			'name' => $name,
    			'sex' => $sex,
    			'phone' => $phone,
    			'email' => $email
    		]);

    	if ($res) {
    		if ($name !== session('user')['name']) {
    			//$request->session()->forget('user');
    			return $common->json(2010,'修改成功，请重新登录');
    		}else{
    			return $common->json(2000,'修改成功');
    		}
    	}else{
    		return $common->json(1403,'修改失败');
    	}
    	//return session('user');

    }

    //地址管理
    public function address()
    { 
    	$id = session('user')['id'];

    	$address = DB::table('address')
    				->select('id', 'linkman', 'telephone', 'province', 'city', 'town', 'dec')
    				->where('uid', $id)
    				->get();
    	//dd($address);
    	return view('Home/Personal/address', ['ress' => $address]);
    }

    //添加地址
    public function addAddress(AddressRequest $resquest)
    { 
    	$id = session('user')['id'];
    	$linkman = $resquest->input('linkman');
    	$phone = $resquest->input('telephone');
    	$pro = $resquest->input('pro');
    	$cit = $resquest->input('city');
    	$area = $resquest->input('area');
    	$dec = $resquest->input('dec');

    	$patten = '/^((0?1[358]\d{9})|((0(10|2[1-3]|[3-9]\d{2}))?[1-9]\d{6,7}))$/';

    	$match = preg_match($patten,$phone);

        if(!$match){
            return redirect('/Home/address')->with('errorTip', '电话号码不规范');
        }
    	
    	if ($pro == '-1' or $cit == '-1') { 

    		
    		return redirect('/Home/address')->with('errorTip', '添加失败');
    	}

    	

    	$prov = DB::table('district')
    				->select('name')
    				->where('id', $pro)
    				->first();
    	$province = $prov->name;

    	$citys = DB::table('district')
    				->select('name')
    				->where('id', $cit)
    				->first();
    	$city = $citys->name;

    	$tow = DB::table('district')
    				->select('name')
    				->where('id', $area)
    				->first();
    	$town = $tow->name;

    	$res = DB::table('address')
    				->insert([
    						'uid' => $id,
    						'linkman' => $linkman,
    						'telephone' => $phone,
    						'province' => $province,
    						'city' => $city,
    						'town' => $town,
    						'dec' => $dec
    					]);
    	if ($res) { 
    		return redirect('/Home/address')->with('errorTip', '添加成功');
    	} else { 
    		return redirect('/Home/address')->with('errorTip', '添加失败');
    	}
    	

    }

    //编辑地址
    public function modifyAddress($id)
    { 
    	$address = DB::table('address')
    				->select('id', 'linkman', 'telephone', 'dec')
    				->where('id', $id)
    				->first();
    	//dd($address);
    	return view('Home/Personal/modifyAddress', ['ress' => $address]);
    }

    //执行修改地址
     public function editAddress(AddressRequest $resquest)
    { 
    	$id = $resquest->input('id');
    	$linkman = $resquest->input('linkman');
    	$phone = $resquest->input('telephone');
    	$pro = $resquest->input('pro');
    	$cit = $resquest->input('city');
    	$area = $resquest->input('area');
    	$dec = $resquest->input('dec');
    	//dd($phone);
    	$patten = '/^((0?1[358]\d{9})|((0(10|2[1-3]|[3-9]\d{2}))?[1-9]\d{6,7}))$/';

    	$match = preg_match($patten,$phone);

        if(!$match){
            return back()->with('errorTip', '电话号码不规范');
        }

    	if ($pro == '-1' or $cit == '-1') { 

    		$res = DB::table('address')
    					->where('id', $id)
    					->update([
    						'linkman' => $linkman,
    						'telephone' => $phone,
    						'dec' => $dec
    						]);
    		//dd($res);	
    		
	    	if ($res) { 
	    		return redirect('/Home/address')->with('errorTip', '修改成功');
	    	} else { 
	    		return back()->with('errorTip', '修改失败');
	    	}
    	} 

    	$res = DB::table('address')
    				->where('id', $id)
					->update([
						'linkman' => $linkman,
						'telephone' => $phone,
						'province' => $pro,
						'city' => $cit,
						'town' => $area,
						'dec' => $dec
						]);
					
		
    	if ($res) { 
    		return redirect('/Home/address')->with('errorTip', '修改成功');
    	} else { 
    		return back()->with('errorTip', '修改失败');
    	}
    }

    //删除地址
    public function deleteAddress($id)
    { 
    	$res = DB::table('address')
    				->where('id', $id)
    				->delete();
    	//dd($address);
    	if ($res) { 
    		return redirect('/Home/address')->with('errorTip', '删除成功');
    	} else { 
    		return back()->with('errorTip', '删除失败');
    	}
    }

    //进入修改密码页面
    public function passChange()
    {
    	return view('Home/Personal/passChange');
    }

    //确认密码
    public function oldPass(Request $request)
    {
    	$common = new CommonController;
    	$id = session('user')['id'];
    	$pass = $request->pass;
    	$user = DB::table('users')
    				->select('id', 'password')
    				->where('id', $id)
    				->first();

    	//$rew = $pass->id;

    	if(password_verify($pass,$user->pass)) {

         	return $common->json(1200, '密码正确');

	    } else {

	        return $common->json(1203, '密码错误');

	    }
    }

    //验证新密码
    public function newPass(Request $request)
    {
    	$common = new CommonController;
    	$npass = $request->npass;

    	//return $request;
    	$patten = '/^(?=.*\d)(?=.*[a-zA-Z])(?=.*[~!@#$%^&*])[\da-zA-Z~!@#$%^&*]{8,16}$/';

   		preg_match($patten,$npass,$match);
   			if($match)
   			{
   				return $common->json(1301, '密码格式正确');

   			}else{

   				return $common->json(1310, '密码必须包含数字、字母和特殊符号且需输入3~16位');

   			}
    }

    //修改密码
    public function modify(Request $request)
    {
    	$common = new CommonController;
    	$id = session('user')['id'];
    	$opass = $request->opass;
    	$npass = $request->npass;
    	$cpass = $request->cpass;

    	if ($npass !== $cpass) {
    		return $common->json(1123, '修改失败');
    	}

    	$res = DB::table('users')->where('id', $id)->update([
    			'pass' => password_hash($npass,PASSWORD_DEFAULT),
    		]);

    	if ($res) {
			return $common->json(2400, '修改成功，请重新登录');
    	}else{
    		return $common->json(1123, '修改失败');
    	}

    }

    //订单管理
    public function order()
    {

    	$id = session('user')['id'];


    	$order = DB::table('orders')
    				->select('id', 'order_number', 'order_time', 'total_money', 'order_state', 'orders.logistics')
    				->where('uid', $id)
    				->orderBy('id', 'desc')
    				->get();

    	$order = DB::table('orders')->select()->where('uid', $id)->orderBy('id', 'desc')->get();


    	$detail = DB::table('orders')
    				->join('order_detail', 'orders.id', '=', 'order_detail.oid')
    				->select()->where('orders.uid', $id)
    				->orderBy('order_detail.id', 'desc')
    				->get();

    	$state = [0=>'进行中', 1=>'已完成', 2=>'已取消'];

    	$status = [0=>'未发出', 1=>'待揽收', 2=>'已收货'];
    	//dd($detail);
    	return view('Home/Personal/order', [
    		'order' => $order,
    		'detail' => $detail,
    		'state' => $state,
    		'status' => $status
    		]);
    }

    // 确认支付
    public function pay($id)
    {
      $time = date('Y-m-d H:i:s');
      $res = DB::table('orders')->where('id', $id)->update([
          'pay_state' => 1,
          'pay_time' => $time,
          'logistics' => 1
        ]);

      if ($res) {
        return redirect('/Home/order')->with('receipt', '成功支付');
      } else {
        return redirect('/Home/order')->with('receipt', '支付失败');
      }

    }


    //确认收货
    public function receipt($id)
    {
        $time = date('Y-m-d H:i:s');
       $shop = DB::table('orders')->join('order_detail','orders.id','=','order_detail.oid')->where('orders.id',$id)->select()->get();
      foreach ($shop as $v) {
        DB::table('integral_record')->insert([
          'user_id'=>$v->uid,
          'change'=>'+'.$v->unit_price,
            'date'=> $time,
          'detail'=>$v->goods_name.$v->goods_specification,
        ]);
      }
        $res = DB::table('orders')->where('id', $id)->update([

                'order_state' => 1,
                'logistics' => 2

            ]);

        if ($res) {
            return redirect('/Home/order')->with('receipt', '收货成功');
        } else {
            return redirect('/Home/order')->with('receipt', '收货失败');
        }

    }

    //取消订单
    public function cancel($id)
    {
      $res = DB::table('orders')->where('id', $id)->update([
                'pay_state' => 2,
          'order_state' => 0,
            ]);

        if ($res) {
            return redirect('/Home/order')->with('cancel', '已提交，等待退款');
        } else {
            return redirect('/Home/order')->with('cancel', '提交失败，请重试');
        }
    }


    //订单详情
    public function orderDetail()
    {


    	return view('Home/Personal/order_detail');

    }

    //进入商品评价页
    public function comment()
    {
    	$uid = session('user')['id'];

    	$evaluate = DB::table('orders')
    				->join('order_detail', 'orders.id', '=', 'order_detail.oid')
    				->select('order_detail.id', 'order_detail.oid', 'order_detail.goods_name', 'order_detail.goods_pic', 'order_detail.goods_specification', 'order_detail.unit_price', 'order_detail.gid')
    				->where([
    						['orders.uid', '=', $uid],
    						['order_detail.evaluate_state', '=', 1],
    					])
    				->orderBy('order_detail.id', 'desc')
    				->get();
    	//dd($evaluate);
    	return view('Home/Personal/comment', ['evaluate' => $evaluate]);
    }

    //执行商品评价
    public function evaluateGoods(Request $request)
    {
    	$id = session('user')['id'];
    	$gid = $request->goods_id;
    	$evaluate = $request->evaluate;
    	$comment = $request->comment;
    	$did = $request->detail_id;
    	//dd($did);
    	if (!$evaluate) { 
    		return back()->with('eval', '请选择评价');
    	}

    	$date = date('Y-m-d H:i:s', time());

    	$res = DB::table('good_comment')
    				->insert([ 
    						'user_id' => $id,
    						'goods_id' => $gid,
    						'evaluate' => $evaluate,
    						'comment' => $comment,
    						'date' => $date
    					]);
    	if ($res) { 

    		$val = DB::table('order_detail')
    				->where('id', $did)
    				->update([ 
    						'evaluate_state' => 2,
    					]);

    		return redirect('/Home/comment')->with('eval', '评论成功');
    	} else { 
    		return back()->with('eval', '评价失败');
    	}

    	//dd($evaluate);
    }

    //我的积分
    public function integral()
    {
    	$id = session('user')['id'];

    	$inte = DB::table('integral_record')
    				->select('detail', 'change', 'date')
    				->where('user_id', $id)
    				->get();

    	$surplus = DB::table('users')
    				->select('surplus_intergral')
    				->where('id', $id)
    				->first();

    	$sur = $surplus->surplus_intergral;
    	//dd($sur);

    	return view('Home/Personal/integral', ['inte' => $inte, 'sur' => $sur]);
    }

    //进入积分商城
    public function integralGoods()
    { 
    	$goods = DB::table('integral_goods')
    				->select('id', 'ig_name', 'image', 'detail', 'integral_price', 'status', 'stock')
    				->get();
    	//dd($goods);
    	return view('Home/Personal/integralGoods', ['goods' => $goods]);
    }

    //进入选地址
    public function exchangeAddress($id)
    { 
    	$uid = session('user')['id'];

    	$res = DB::table('users')
    				->select('surplus_intergral')
    				->where('id', $uid)
    				->first();

    	$address = DB::table('address')
    				->select('id', 'linkman', 'telephone', 'province', 'city', 'town', 'dec')
    				->where('uid', $uid)
    				->get();

    	$goods = DB::table('integral_goods')
    				->select('id', 'ig_name', 'image', 'detail', 'integral_price', 'status', 'stock')
    				->where('id', $id)
    				->first();
    	//dd($res);
    	if ($goods->stock < 1) { 
    		return back()->with('iprice', '库存不足');
    	}

    	if ($res->surplus_intergral < $goods->integral_price) { 
    		return back()->with('iprice', '你的积分不够');
    	}
    	//dd($address);
    	return view('Home/Personal/exchangeAddress', ['ress' => $address, 'goods' => $goods]);
    }

    //积分订单添加地址
    public function appendAddress(AddressRequest $resquest)
    { 
    	$common = new CommonController;
    	$id = session('user')['id'];
    	$linkman = $resquest->input('linkman');
    	$phone = $resquest->input('telephone');
    	$province = $resquest->input('pro');
    	$city = $resquest->input('city');
    	$town = $resquest->input('area');
    	$dec = $resquest->input('dec');

    	$patten = '/^((0?1[358]\d{9})|((0(10|2[1-3]|[3-9]\d{2}))?[1-9]\d{6,7}))$/';

    	$match = preg_match($patten,$phone);

        if(!$match){
            return $common->json(2000, '电话号码不规范');
        }
        //dd($province);
        if ($province == "--请选择省份--" or $city == "--请选择城市--") { 
        	return $common->json(2000, '请选择所在地');
        }
    	$res = DB::table('address')
    				->insert([
    						'uid' => $id,
    						'linkman' => $linkman,
    						'telephone' => $phone,
    						'province' => $province,
    						'city' => $city,
    						'town' => $town,
    						'dec' => $dec
    					]);
    	if ($res) { 
    		return $common->json(2010, '添加成功');
    	} else { 
    		return $common->json(2000, '添加失败');
    	}
    	

    }

    //积分订单删除地址
    public function deleteIntAddress($id)
    { 
    	$res = DB::table('address')
    				->where('id', $id)
    				->delete();
    	//dd($address);
    	if ($res) { 
    		return back()->with('addr', '删除成功');
    	} else { 
    		return back()->with('addr', '删除失败');
    	}
    }

    //提交积分订单
    public function submitIntegralOrder(submitIntegralOrderRequest $request)
    {
    	$common = new CommonController;
    	$uid = session('user')['id'];
    	$name = $request->name;
    	$oid = $request->integral_goods_id;
    	$addressId = $request->addressId;
    	$price = $request->integral_price;
    	//dd($price);
    	//dd($name);
    	$address = DB::table('address')
    				->select('linkman', 'telephone', 'province', 'city', 'town', 'dec')
    				->where('id', $addressId)
    				->first();
    	$ress = $address->province.$address->city.$address->town.$address->dec;

    	$sur = DB::table('users')
    				->select('surplus_intergral')
    				->where('id', $uid)
    				->first();
    	$surplus = $sur->surplus_intergral;

    	$date = date('Y-m-d H:i:s', time());

    	if ($surplus < $price) { 
    		return $common->json(3000, '你的积分不够');
    	} else { 
    		$newSur = $surplus - $price;
    		//减少用户表里的剩余积分
    		$val = DB::table('users')
    				->update(['surplus_intergral' => $newSur]);
    		
    		$delIntegral = "兑换了".$name."商品";
    		$conIntegral = "-".$price;
    		//插入积分详情表
    		$vals = DB::table('integral_record')
    				->insert([ 
    						'user_id' => $uid,
    						'detail' => $delIntegral,
    						'change' => $conIntegral,
    						'date' => $date
    					]);
    		if (!$val) { 
    			return $common->json(3000, '下单失败');
    		}

    		if (!$vals) { 
    			return $common->json(3000, '下单失败');
    		}
    	}

    	

    	$res = DB::table('integral_order')
    				->insert([ 
    						'user_id' => $uid,
    						'integral_goods_id' => $oid,
    						'order_number' => time(),
    						'generation_time' => $date,
    						'number' => '1',
    						'consignee' => $address->linkman,
    						'phone' => $address->telephone,
    						'address' => $ress,
    						'integral_price' => $price,
    						'order_status' => '0'
    					]);

    	if ($res) { 

    		$stocks = DB::table('integral_goods')
    					->select('stock')
    					->where('id', $oid)
    					->first();

    		$newStock = $stocks->stock - 1;

    		$values = DB::table('integral_goods')
    					->update([ 
    							'stock' => $newStock,
    						]);

    		return $common->json(3010, '下单成功');
    	} else { 
    		return $common->json(3000, '下单失败');
    	}
    
	}


	//进入我的积分订单
	public function integralOrder()
	{ 
		$id = session('user')['id'];

		$orders = DB::table('integral_order')
					->join('integral_goods', 'integral_order.integral_goods_id', '=', 'integral_goods.id')
					->select('integral_order.id', 'integral_order.order_number', 'integral_order.generation_time', 'integral_order.number', 'integral_order.consignee', 'integral_order.order_status', 'integral_order.integral_price', 'integral_order.consignee', 'integral_order.phone', 'integral_order.address', 'integral_goods.ig_name', 'integral_goods.image')
					->where('integral_order.user_id', $id)
					->orderBy('id', 'desc')
					->get();
		//dd($orders);
		$state = [0=>'正在出货', 1=>'已发货', 2=>'已收货', 3=>'已失效'];



		return view('Home/Personal/integralOrder', ['orders' => $orders, 'state' => $state]);

	}


	//确认收货积分订单
	public function saidIntegral($id)
	{ 
		
		$res = DB::table('integral_order')
					->where('id', $id)
					->update([ 
							'order_status' => 2
						]);
		if ($res > 0) {
			return redirect('/Home/integralOrder')->with('success', '收货成功');
		} else { 
			return back()->with('fails', '收货失败');
		}
	}

	//删除积分订单 
	public function deleteIntOrder($id)
	{
		
		$res = DB::table('integral_order')
					->where('id', $id)
					->delete();

		if ($res > 0) {
			return redirect('/Home/integralOrder')->with('success', '删除成功');
		} else { 
			return back()->with('fails', '删除失败');
		}


	}

    //收藏
    public function collection()

    { 
    	$id = session('user')['id'];

    	$pri = DB::table('collection')
    				->join('shop_price', 'collection.goods_id', '=', 'shop_price.gid')
    				->select(DB::raw('min(shop_price.price) as price'))
    				->where('collection.user_id', $id)
    				->groupBy('collection.goods_id')
    				->get()->toArray();

    	$goods = DB::table('collection')
    				->join('shop_goods', 'collection.goods_id', '=', 'shop_goods.id')
    				->join('shop_text', 'shop_goods.id', '=', 'shop_text.gid')
    				->select('collection.id', 'collection.goods_id', 'shop_goods.pic', 'shop_goods.status', 'shop_goods.goods_sales', 'shop_text.attribute')
    				->where('collection.user_id', $id)
    				->orderBy('collection.id', 'desc')
    				->get()->toArray();
    	//dd($goods);
		
    	foreach ($goods as $k=>&$v) { 
    		for($p = 0; $p < count($goods); $p++) {
    			if ($p == $k) { 
    				$t = $pri[$p]->price;
    				$v->price = $t;
    			}
    		}
    	}
    	//dd($goods);
    	return view('Home/Personal/collection', ['goods' => $goods]);
    }

    //删除收藏
    public function cancelCollection($id) 
    { 
    	$res = DB::table('collection')
    				->where('id', $id)
    				->delete();
    	if ($res) { 
    		return redirect('/Home/collection');
    	} else { 
    		return redirect('/Home/collection');
    	}	

    }

}
